package CAS;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class TestAccount {
    public static void main(String[] args) {

        AccountUnsafe accountUnsafe = new AccountUnsafe(10000);
        Account.demo(accountUnsafe);
    }
}

class AccountUnsafe implements Account {
    private Integer balance;

    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
        return this.balance;
    }

    @Override
    public void withdraw(Integer amount) {
        //synchronized (this) {
            this.balance = this.balance - amount;
        //}

    }
}

interface Account{
    //获取余额
    Integer getBalance();

    //取款
    void withdraw(Integer amount);

    /**
     * 方法内会启动1000个线程，每个线程做-10元的操作
     * 如果初始余额为10000，那么正确的结果应当是0
     */
    static void demo(Account account){
        ReentrantLock lock = new ReentrantLock();


        List<Thread> ts = new ArrayList<Thread>();
        for (int i = 0; i < 1000; i++) {
           Thread t = new Thread(()->{
                    //lock.lock();
                    try {
                        account.withdraw(10);
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                       // lock.unlock();
                    }
            });
           t.start();
           ts.add(t);
        }
        long startTime = System.currentTimeMillis();
//        ts.forEach(Thread::start);
        ts.forEach(t->{
            try{
                t.join();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        });
        long endTime = System.currentTimeMillis();
        System.out.println("余额:"+account.getBalance()+",cost:"+String.valueOf(endTime-startTime));
    }
}
